<template>
  <div class="step">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-position="top" class="demo-ruleForm">
      <el-form-item label="商户名称" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请输入商户名称"></el-input>
      </el-form-item>
      <el-form-item label="服务电话" prop="serverPhone">
        <el-input v-model.number="ruleForm.serverPhone" placeholder="请输入服务电话"></el-input>
      </el-form-item>
      <el-form-item label="商户地址" required>
        <el-row type="flex">
            <el-form-item prop="province">
              <el-select
                size="small"
                style="width:160px"
                v-model="ruleForm.province"
                placeholder="请选择省份"
                @change="provinceChange"
              >
                <el-option
                  v-for="item in addressOptions.province"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="city">
              <el-select
                size="small"
                style="width:160px"
                v-model="ruleForm.city"
                placeholder="请选择城市"
                @change="cityChange"
              >
                <el-option
                  v-for="item in addressOptions.city"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="region">
              <el-select
                size="small"
                style="width:160px"
                v-model="ruleForm.region"
                placeholder="请选择市区"
                @change="areaChange"
              >
                <el-option
                  v-for="item in addressOptions.area"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="town">
              <el-select
                size="small"
                style="width:160px"
                v-model="ruleForm.town"
                placeholder="请选择街道( 可空 )"
                @change="streetChange"
              >
                <el-option
                  v-for="item in addressOptions.street"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-row>
      </el-form-item>
       <el-form-item label="详细地址" prop="detail">
        <el-input
          size="medium "
          v-model="ruleForm.detail"
          placeholder="点击获取定位地址"
          suffix-icon="el-icon-location-information"
          @focus="openTmap"
        ></el-input>
      </el-form-item>
      <el-form-item label="确切地址" prop="addressRemarks">
        <el-input v-model="ruleForm.addressRemarks" placeholder="请输入门牌号详细地址......"></el-input>
      </el-form-item>
      <el-form-item label="经营课程" prop="categoryIds">
        <el-tag
          style="margin-right:5px"
          v-for="tag in ruleForm.categoryIds"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)">
          {{tags(tag)}}
        </el-tag>
      </el-form-item>
      <el-form-item  prop="categoryIds">
             <el-tabs v-model="activeName">
              <el-tab-pane
              v-for="item in categoryAllList"
              :key="item.id"
              :label="item.name"
              :name="item.id">
                <!-- <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll[index]" @change="handleCheckAllChange">全选</el-checkbox> -->
                <div style="margin: 15px 0;"></div>
                <el-checkbox-group v-model="ruleForm.categoryIds">
                  <el-checkbox v-for="categories in item.categories" :label="categories.id" :key="categories.id">{{categories.name}}</el-checkbox>
                </el-checkbox-group>
              </el-tab-pane>
            </el-tabs>
      </el-form-item>
      <el-form-item label="商户品牌标识" prop="logoImg">
        <el-upload
          drag
          action="#"
          :class="{disabled:isMax}"
          list-type="picture-card"
          :limit="1"
          :file-list="business.fileList"
          :on-change="onChange"
          :before-upload="beforeAvatarUpload"
          :on-preview="handleBusinessLogoPreview"
          :on-remove="handleRemove"
          :http-request="businessLogo">
            <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="business.visible">
          <img width="100%" :src="business.imageUrl" alt="">
        </el-dialog>
        <span style="color:#cccc;margin-top:30px;display:inline-block;">支持jpg.格式图片大小不低于4M</span>
      </el-form-item>
      <el-form-item label="法人身份证（正面）" prop="idCardImg">
        <el-upload
          drag
          action="#"
          list-type="picture-card"
          :class="{disabled:idInfo.isMax}"
          class="idimg"
          :limit="1"
          :file-list="idInfo.fileList"
          :on-change="onIdInfoChange"
          :before-upload="beforeAvatarUpload"
          :on-preview="handleIdPreview"
          :on-remove="handleIdInfoRemove"
          :http-request="httpRequestIdInfo">
            <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="idInfo.visible">
          <img width="100%" :src="idInfo.imageUrl" alt="">
        </el-dialog>
        <span style="color:#cccc;margin-top:30px;display:inline-block;">注：证件必须是清晰、显示完整的彩色原件电子版本，可以是扫描件或者数码拍摄照片。</span>
      </el-form-item>
      <el-form-item label="营业执照" prop="certificateImg">
        <el-upload
          drag
          action="#"
          list-type="picture-card"
          :class="{disabled:license.isMax}"
          class="idimg"
          :limit="1"
          :file-list="license.fileList"
          :on-change="onLicenseChange"
          :before-upload="beforeAvatarUpload"
          :on-preview="handleLicensePreview"
          :on-remove="handleLicenseRemove"
          :http-request="httpRequestLicense">
            <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="license.visible">
          <img width="100%" :src="license.imageUrl" alt="">
        </el-dialog>
        <span style="color:#cccc;margin-top:30px;display:inline-block;">注：证件必须是清晰、显示完整的彩色原件电子版本，像素分辨率在500*500-2000*2000为最佳分辨率。</span>
      </el-form-item>
      <el-form-item>
        <div class="submit" @click="timer===5 && submitForm('ruleForm')">提交审核</div>
      </el-form-item>
    </el-form>
    <!-- 地图 -->
     <el-dialog
      title="选择地址"
      :visible.sync="addressOptions.dialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @close="1"
      width="750px"
    >
      <div ref="mapArry" style="width:100%;height:600px">
        <iframe
          id="mapPage"
          width="100%"
          height="100%"
          frameborder="0"
          src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=R6GBZ-ZPH6S-F6XOL-6OEWC-VZNX2-GKFMY&referer=myapp"
        ></iframe>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { setAuditStatus } from '@/utils/auth'
import { randomString } from '@/utils'

import {
  provinceList,
  cityList,
  areaList,
  streetList,
  getCategoryAll,
  getBusinessCertify
} from '@/api/common'
import { getAllLabels, merchantType, businessRegister } from '@/api/user'

export default {
  name: 'Step2',
  inject: ['reload'],
  props: ['businessId'],
  data() {
    return {
      certifyId: '',
      timer: 5,
      isHttp: true,
      addressOptions: {
        dialog: false,
        province: [], // 省
        city: [],
        area: [],
        street: [],
        searchAdress: '',
        options: [],
        lat: '',
        lng: '',
        currentCity: ''
      },
      allLabels: [],
      activeName: '1',
      categoryAllList: [], // 所有分类集合
      checkAll: [],
      isIndeterminate: true,
      checkedCities: [],
      categorySonItem: [], // 子分类
      schoolForm: {
        topTypeIndex: '0',
        allTypeList: [],
        topTypeList: [],
        childrenType: [],
        chooseTypes: [],
        checkTypeAll: false,
        chooseTag: [],
        isTypeIndeterminate: true,
        valueData: {
          categoryIds: '',
          categoryNames: ''
        }
      },
      business: {
        visible: false,
        fileList: [],
        imageUrl: ''
      },
      idInfo: {
        isMax: false,
        visible: false,
        fileList: [],
        imageUrl: ''
      },
      license: {
        isMax: false,
        visible: false,
        fileList: [],
        imageUrl: ''
      },
      dialogImageUrl: '',
      dialogVisible: false,
      isMax: false,
      ruleForm: {
        name: '',
        serverPhone: '',
        province: '',
        city: '',
        region: '',
        town: '',
        detail: '',
        lat: '',
        lng: '',
        addressRemarks: '',
        addressIds: '',
        checkList: [],
        categoryIds: [],
        categoryNames: [],
        logoImg: '',
        idCardImg: '',
        idObjectKey: '',
        certificateImg: '',
        certificateObjectKey: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入商户名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        serverPhone: [
          { required: true, message: '请输入服务电话', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择省份', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请选择城市', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请选择市区', trigger: 'blur' }
        ],
        town: [
          { message: '请选择街道', trigger: 'blur' }
        ],
        detail: [
          { required: true, message: '请选择地址', trigger: 'change' }
        ],
        addressRemarks: [
          { required: true, message: '请填写确切地址', trigger: 'blur' }
        ],
        categoryIds: [
          { required: true, message: '请选择经营课程', trigger: 'blur' }
        ],
        logoImg: [
          { required: true, message: '请上传商户品牌标识', trigger: 'change' }
        ],
        idCardImg: [
          { required: true, message: '请上传身份证正面照片', trigger: 'change' }
        ],
        certificateImg: [
          { required: true, message: '请上传营业执照', trigger: 'change' }
        ]
      }
    }
  },
  filters: {
    // tags(tag) {
    //   const t = tag.split(':')
    //   return t[1]
    // }
  },
  computed: {
    ...mapGetters([
      'auditStatus'
    ]),
    tags() {
      return function name(tag) {
        const tagList = []
        this.categoryAllList.forEach(i => {
          tagList.push(...i.categories)
        })
        const t = tagList.find(i => i.id === tag)
        return t.name
      }
    }
  },
  created() {
    this.getData()
    this.businessId && this.getBusinessInfo()
  },
  mounted() {
    const that = this
    window.addEventListener(
      'message',
      function(event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data
        if (loc && loc.module == 'locationPicker') {
          // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          // console.log('location', loc)
          that.ruleForm.lat = loc.latlng.lat
          that.ruleForm.lng = loc.latlng.lng
          that.ruleForm.detail = `${loc.poiaddress}${loc.poiname}`
        }
      },
      false
    )
    that.isHttp = location.protocol === 'https:'
  },
  methods: {
    // 省
    provinceChange(v) {
      this.ruleForm.city = null
      this.ruleForm.region = null
      this.ruleForm.town = null
      cityList({
        pid: v
      }).then(res => {
        this.addressOptions.city = res.data.map(i => {
          return {
            label: i.cityName,
            value: i.cityCode,
            lat: i.lat,
            lng: i.lng
          }
        })
      })
    },
    // 市
    cityChange(v) {
      this.ruleForm.region = null
      this.ruleForm.town = null
      areaList({
        pid: v
      }).then(res => {
        this.addressOptions.area = res.data.map(i => {
          return {
            label: i.areaName,
            value: i.areaCode,
            lat: i.lat,
            lng: i.lng
          }
        })
      })
    },
    // 区
    areaChange(v) {
      this.ruleForm.town = null
      streetList({
        pid: v
      }).then(res => {
        this.addressOptions.street = res.data.map(i => {
          return {
            label: i.streetName,
            value: i.streetCode,
            lat: i.lat,
            lng: i.lng
          }
        })
      })
      const s = this.addressOptions.province.find(i => i.value === this.ruleForm.province).label
      const c = this.addressOptions.city.find(i => i.value === this.ruleForm.city).label
      const q = this.addressOptions.area.find(i => i.value === this.ruleForm.region).label
      this.ruleForm.addressRemarks = `${s}${c}${q}`
    },
    // 街道
    streetChange(v) {
      const s = this.addressOptions.province.find(i => i.value === this.ruleForm.province).label
      const c = this.addressOptions.city.find(i => i.value === this.ruleForm.city).label
      const q = this.addressOptions.area.find(i => i.value === this.ruleForm.region).label
      const j = this.addressOptions.street.find(i => i.value === v).label
      this.ruleForm.addressRemarks = `${s}${c}${q}${j}`
    },
    openTmap(v) {
      this.addressOptions.dialog = true
    },
    handleClose(tag) {
      this.schoolForm.chooseTypes.splice(this.schoolForm.chooseTypes.indexOf(tag), 1)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 4

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 4MB!')
      }
      return isJPG && isLt2M
    },
    // 商户标识
    businessLogo(res, fileList) {
      // this.ruleForm.logoImg = URL.createObjectURL(res.file)
      const raw = {
        raw: res.file,
        name: new Date().valueOf()
      }
      this.uploadImgToOss(raw, true, true).then(response => {
        const { imgUrl } = response
        this.ruleForm.logoImg = imgUrl
      }).finally(() => {
      })
    },
    onChange(file, fileList) {
      console.log(123);
      this.isMax = fileList.length >= 1
    },
    handleRemove(file, fileList) {
      this.isMax = fileList.length >= 1
      this.ruleForm.logoImg = ''
    },
    // 身份证正面
    httpRequestIdInfo(res, fileList) {
      // this.ruleForm.idCardImg = URL.createObjectURL(res.file)
      const raw = {
        raw: res.file,
        name: new Date().valueOf()
      }
      this.uploadImgToOss(raw, false, this.isHttp).then(response => {
        const { imgUrl, fileKey } = response
        this.ruleForm.idCardImg = imgUrl
        this.ruleForm.idObjectKey = fileKey
      })
    },
    onIdInfoChange(file, fileList) {
      this.idInfo.isMax = fileList.length >= 1
    },
    handleIdPreview(file) {
      this.idInfo.imageUrl = file.url
      this.idInfo.visible = true
    },
    handleIdInfoRemove(file, fileList) {
      this.idInfo.isMax = fileList.length >= 1
      this.ruleForm.idCardImg = ''
    },
    // 营业执照
    httpRequestLicense(res, fileList) {
      // this.ruleForm.certificateImg = URL.createObjectURL(res.file)
      const raw = {
        raw: res.file,
        name: new Date().valueOf()
      }
      this.uploadImgToOss(raw, false, this.isHttp).then((response) => {
        const { imgUrl, fileKey } = response
        this.ruleForm.certificateImg = imgUrl
        this.ruleForm.certificateObjectKey = fileKey
      })
    },
    onLicenseChange(file, fileList) {
      this.license.isMax = fileList.length >= 1
    },

    handleBusinessLogoPreview(file) {
      this.business.imageUrl = file.url
      this.business.visible = true
    },

    handleLicensePreview(file) {
      this.license.imageUrl = file.url
      this.license.visible = true
    },
    handleLicenseRemove(file, fileList) {
      this.license.isMax = fileList.length >= 1
      this.ruleForm.certificateImg = ''
    },
    throttle(f, wait) {
      let timer
      return (...args) => {
        if (timer) { return }
        timer = setTimeout(() => {
          f(...args)
          timer = null
        }, wait)
      }
    },
    submitForm(formName) {
      let confirm = false
      this.$refs[formName].validate((valid) => {
        if (valid) {
          confirm = true
        } else {
          console.log('error submit!!')
          return false
        }
      })
      if (!confirm) return
      // 所有子分类
      const categoryArr = []
      this.categoryAllList.forEach(i => {
        categoryArr.push(...i.categories)
      })
      // 选中的子分类对象
      const same = categoryArr.filter(i => {
        return this.ruleForm.categoryIds.indexOf(i.id) !== -1
      })
      // 选中的子分类name
      const categoryNames = same.map(i => {
        return i.name
      })
      // 选中的父分类id
      const parentIds = same.map(i => {
        return i.parentId
      })
      const categoryParentIds = Array.from(new Set(parentIds))
      const categoryParentNames = []
      const classify = []
      // 选中的父分类对象集合
      const parentObj = this.categoryAllList.filter(i => {
        return categoryParentIds.indexOf(i.id) !== -1
      })
      parentObj.forEach(i => {
        categoryParentNames.push(i.name)
        classify.push(i.classify)
      })
      let type = null
      const classifytype = [...new Set(classify)]
      const p = classifytype.reduce((prev, curr) => {
        return prev + curr
      })
      switch (p) {
        case 1:
          type = 1
          break
        case 2:
          type = 2
          break
        case 3:
          type = 3
          break
      }
      this.timer = 4
      const time = setInterval(() => {
        this.timer--
        if (this.timer <= 0) {
          clearInterval(time)
          this.timer = 5
        }
      }, 1000)
      const s = this.addressOptions.province.find(i => i.value === this.ruleForm.province).label
      const c = this.addressOptions.city.find(i => i.value === this.ruleForm.city).label
      const q = this.addressOptions.area.find(i => i.value === this.ruleForm.region).label
      const j = this.ruleForm.town && this.addressOptions.street.find(i => i.value === this.ruleForm.town).label
      this.ruleForm.addressIds = `${this.ruleForm.province},${this.ruleForm.city},${this.ruleForm.region},${this.ruleForm.town||''}`
      // console.log(this.ruleForm, s, c, q, j, 'this.ruleForm')
      businessRegister({
        'certify': {
          'id': this.certifyId || '',
          'idCardImg': this.ruleForm.idCardImg,
          'certificateImg': this.ruleForm.certificateImg,
          'idObjectKey': this.ruleForm.idObjectKey,
          'certificateObjectKey': this.ruleForm.certificateObjectKey
        },
        'business': {
          'id': this.businessId || null,
          'name': this.ruleForm.name,
          'serverPhone': this.ruleForm.serverPhone,
          'isCertified': false,
          'synopsis': '',
          'score': 5,
          'status': 1,
          'collectionCount': 0,
          'commentCount': 0,
          'viewCount': 0,
          'teachCount': 0,
          'addressIds': this.ruleForm.addressIds,
          'province': s,
          'city': c,
          'region': q,
          'town': j,
          'detail': this.ruleForm.detail,
          'lat': this.ruleForm.lat,
          'lng': this.ruleForm.lng,
          'synopsisImg': '',
          'categoryParentIds': categoryParentIds.join(','),
          'categoryParentNames': categoryParentNames.join(','),
          'categoryIds': this.ruleForm.categoryIds.join(','),
          'categoryNames': categoryNames.join(','),
          'studentCount': '',
          'foundTime': '',
          'type': type,
          'logoImg': this.ruleForm.logoImg,
          'addressRemarks': this.ruleForm.addressRemarks
        }
      }).then(res => {
        setAuditStatus('1')
        this.$store.commit('user/SET_AUDITSTATUS', '1')
        this.$emit('reload')
        this.$message({
          message: '提交成功',
          type: 'success'
        })
      })
    },
    getData() {
      // 省
      provinceList().then(res => {
        this.addressOptions.province = res.data.map(i => {
          return {
            label: i.provinceName,
            value: i.provinceCode,
            lat: i.lat,
            lng: i.lng
          }
        })
      })
      // 课程分类
      getCategoryAll().then(res => {
        this.categoryAllList = res.data
      })
      // 经营课程
      getAllLabels({
        status: 1,
        type: null
      }).then(res => {
        this.allLabels = res.data
      })
    },
    getBusinessInfo() {
      getBusinessCertify({
        'businessId': this.businessId
      }).then(res => {
        const { business, certify } = res.data
        const address = business.addressIds.split(',')
        cityList({
          pid: address[0]
        }).then(res => {
          this.addressOptions.city = res.data.map(i => {
            return {
              label: i.cityName,
              value: i.cityCode,
              lat: i.lat,
              lng: i.lng
            }
          })
        })
        areaList({
          pid: address[1]
        }).then(res => {
          this.addressOptions.area = res.data.map(i => {
            return {
              label: i.areaName,
              value: i.areaCode,
              lat: i.lat,
              lng: i.lng
            }
          })
        })
        streetList({
          pid: address[2]
        }).then(res => {
          this.addressOptions.street = res.data.map(i => {
            return {
              label: i.streetName,
              value: i.streetCode,
              lat: i.lat,
              lng: i.lng
            }
          })
        })
        this.certifyId = certify.id
        this.ruleForm.name = business.name
        this.ruleForm.serverPhone = business.serverPhone
        this.ruleForm.province = address[0]
        this.ruleForm.city = address[1]
        this.ruleForm.region = address[2]
        this.ruleForm.town = address[3]
        this.ruleForm.addressIds = business.addressIds
        this.ruleForm.lat = business.lat
        this.ruleForm.lng = business.lng
        this.ruleForm.addressRemarks = business.addressRemarks
        this.ruleForm.detail = business.detail
        this.ruleForm.categoryIds = business.categoryIds || []
        this.ruleForm.logoImg = business.logoImg
        this.ruleForm.idCardImg = certify.idCardImg
        this.ruleForm.idObjectKey = certify.idObjectKey
        this.ruleForm.certificateImg = certify.certificateImg
        this.ruleForm.certificateObjectKey = certify.certificateObjectKey

        this.business.fileList = [{ url: business.logoImg }]
        this.isMax = !!business.logoImg

        this.idInfo.fileList = [{ url: certify.idCardImg }]
        this.idInfo.isMax = !!certify.idCardImg

        this.license.fileList = [{ url: certify.certificateImg }]
        this.license.isMax = !!certify.certificateImg

        this.business.imageUrl = business.logoImg
        this.idInfo.imageUrl = certify.idCardImg
        this.license.imageUrl = certify.certificateImg
        // console.log(res, 'sss')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .step{
    padding: 20px;
    width: 100%;
    .title{
      width: 100%;
      height: 50px;
      display: flex;
      align-items: center;
      font-size:14px;
      font-family:PingFang SC;
      font-weight:600;
      color:rgba(77,92,101,1);
      border-bottom: 1px solid #EEEEEE;
    }

   .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    /deep/.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    .logoimg{
      width:112px;
      height:112px;
      background:rgba(245,247,251,1);
      border-radius:3px;
    }
    .submit{
      margin-top: 50px;
      cursor: pointer;
      display: flex;
      justify-content: center;
      align-items: center;
      width:237px;
      height:53px;
      font-size:18px;
      font-family:PingFang SC;
      font-weight:500;
      color:rgba(255,255,255,1);
      background:rgba(66,232,202,1);
      border-radius:5px;
    }
  }
  /deep/.el-input{
    width: 100%;
  }
  /deep/.el-input__inner {
    // height: 0.45rem;
    // font-size: 0.14rem;
    font-family: SF UI Display;
    font-weight: bold;
    color: #4D5C65;
    background: rgba(247, 248, 252, 1);
    opacity: 1;
    border:1px solid rgb(218, 228, 233);
    // border-radius: 0.08rem;
    &::-webkit-input-placeholder {
      /* WebKit browsers */
      // font-size: 0.2rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: rgba(217, 220, 227, 1);
    }
  }
    .disabled /deep/.el-upload--picture-card{
        display: none
    }
    .idimg /deep/.el-upload-list--picture-card .el-upload-list__item{
      width:392px;
      height:238px;
      background:rgba(245,247,251,1);
      border-radius:5px;
    }
</style>
